"use client"
import { AntdRegistry } from "@ant-design/nextjs-registry"
import "./globals.css"
import BasicLayout from "@/layouts/basic-layout"
import React, { useCallback, useEffect } from "react"
import { Provider } from "react-redux"
import store, { useAppDispatch } from "@/stores"
import AccessLayout from "@/access/access-layout"
import { getLoginUser } from "@/api/user"
import { setLoginUserAction } from "@/stores/features/login-user"

// 全局初始化逻辑
const InitLayout: React.FC<
  Readonly<{
    children: React.ReactNode
  }>
> = ({ children }) => {
  const dispatch = useAppDispatch()

  // 初始化用户状态
  const doInitLoginUser = useCallback(async () => {
    const res = await getLoginUser()
    if (res.data) {
      dispatch(setLoginUserAction(res.data))
    }
  }, [])

  useEffect(() => {
    doInitLoginUser()
  }, [])

  return <>{children}</>
}

export default function RootLayout({
  children
}: Readonly<{
  children: React.ReactNode
}>) {
  return (
    <html lang="en">
      <body>
        <AntdRegistry>
          <Provider store={store}>
            <InitLayout>
              <BasicLayout>
                <AccessLayout>{children}</AccessLayout>
              </BasicLayout>
            </InitLayout>
          </Provider>
        </AntdRegistry>
      </body>
    </html>
  )
}
